import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { resetRouter } from '@/router'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/auth-redirect', '/bind', '/register']

router.beforeEach((to, from, next) => {
  NProgress.start()
  console.log(to, 'to目的路由')
  console.log(from, 'from从哪里来')
  if (getToken()) {
    to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    /* has token*/
    if (to.path === '/dashboard') {
      next()
      NProgress.done()
    }
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (store.getters.roles.length === 0) {
        // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(() => {
          store.dispatch('GenerateRoutes').then(accessRoutes => {
            // resetRouter() // 重置路由(防止重复添加)
            // 根据roles权限生成可访问的路由表
            console.log('router-----------', accessRoutes)
            const acc = accessRoutes
            // 循环第一层
            for (let i = 0; i < acc.length; i++) {
              const element = acc[i]
              // 如果第二层有children
              if (element.children && element.children.length > 0) {
                // 就循环第二层
                for (let j = 0; j < element.children.length; j++) {
                  const item = element.children[j]
                  // 把警告里的name全列举上
                  if (
                    item.name === 'CourseCenter' ||
                    item.name === 'Troops' ||
                    item.name === 'Organizational' ||
                    item.name === 'Equipment' ||
                    item.name === 'Task' ||
                    item.name === 'Material' ||
                    item.name === 'Expert' ||
                    item.name === 'PlanManagement' ||
                    item.name === 'AddressList' ||
                    item.name === 'Info' ||
                    item.name === 'Filter' ||
                    item.name === 'CompanyMessage' ||
                    item.name === 'Consult' ||
                    item.name === 'Risk'
                  ) {
                    // 改造这个name（relax！改name不会有任何冲突）
                    acc[i].children[j].name = ''
                  }
                }
              }
            }

            router.addRoutes(accessRoutes) // 动态添加可访问路由表
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
          })
        }).catch(err => {
          store.dispatch('LogOut').then(() => {
            console.log('err-------------------------------', err)
            Message.error(err.message)
            next({ path: '/' })
          })
        })
      } else {
        next()
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
